package com.flong.utils.annotation.aspect;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.flong.entity.User;
import com.flong.utils.ObjectUtil;
import com.flong.utils.WebUtils;
import com.flong.vo.ResultVo;

/**
 * @Description	 spring-boot-starter-aop
 * https://www.jianshu.com/p/60d719f123bd
 * https://segmentfault.com/a/1190000012845239
 * 
 * http://blog.csdn.net/java_zone/article/details/52861930
 * 
 * Aspect-->> https://www.cnblogs.com/ssslinppp/p/5845659.html
 * 
 * aop切面事务-->> http://blog.csdn.net/bao19901210/article/details/41724355
 * 
 * @ClassName	ControllerAspect
 * @Date		2018年2月23日 下午5:26:47
 * @Author		liangjl
 * @Copyright (c) All Rights Reserved, 2018.
 */
@Aspect
@Component
public class PermissionAspect {
	private final static Logger logger = LoggerFactory.getLogger(PermissionAspect.class);
    
    /**
     * 定义切点
     */
    @Pointcut("@annotation(com.flong.utils.annotation.NeedLogin)")
    public void privilege(){}

    /**
     * 权限环绕通知
     * @param joinPoint
     * @throws Throwable
     */
    @ResponseBody
    @Around("privilege()")
    public Object isAccessMethod(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取访问目标方法
        //MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();
        // Method targetMethod = methodSignature.getMethod();
    	
        Object result = null;//返回的结果
        //返回方法参数
        Object[] args = joinPoint.getArgs();
    	
        for(Object arg : args){
            //获取request请求
            if(arg instanceof HttpServletRequest){
                HttpServletRequest request = (HttpServletRequest) arg;
                //判断用户是否登录
                if(!WebUtils.isLogin(request)){
                    result = new ResultVo(1,"没有登录");
                    logger.debug("没有登录");
                }else {
                	User user = WebUtils.getSessionCurrentUser(request);
                	if(ObjectUtil.isEmpty(user)) {
                		logger.debug("用户信息为："+JSON.toJSONString(user));
                	}
                }
            }
        }
        try{
        	//result为空证明是已经登录.
            if(result == null) {
                // 一切正常的情况下，继续执行被拦截的方法
                result = joinPoint.proceed();
            }
        }catch (Throwable e){
        	result = new ResultVo(1,"发生异常");
        }
    	return result;
    
    }

	
	 
}